﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PatientManagement.Database;
using PatientManagement.Managers;

namespace PatientManagement
{
    public partial class FormPatientManagement : Form
    {
        private List<Patient> m_Patients;
        public FormPatientManagement()
        {
            InitializeComponent();
            InitControl();
            GetPatients();
        }

        private void InitControl()
        {
            dtgPatient.AutoGenerateColumns = false;
            colSex.DataSource = new List<object> { new { Id = true, Value = "Nam" }, new { Id = false, Value = "Nữ" } };
            colSex.ValueMember = "Id";
            colSex.DisplayMember = "Value";
        }

        private void GetPatients()
        {
            m_Patients = ServiceManager.Instance.GetAllPatients();
            dtgPatient.DataSource = m_Patients;
            lbTotalPatient.Text = m_Patients.Count.ToString();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var filterData = m_Patients;
            if (!string.IsNullOrEmpty(tbName.Text))
            {
                filterData = filterData.Where(x => x.Name.ToLower().Contains(tbName.Text.ToLower())).ToList();
            }
            if (!string.IsNullOrEmpty(tbAddress.Text))
            {
                filterData = filterData.Where(x => x.Address.ToLower().Contains(tbAddress.Text.ToLower())).ToList();
            }

            dtgPatient.DataSource = filterData;
            lbTotalPatient.Text = filterData.Count.ToString();   
        }

        private void dtgPatient_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (dtgPatient.Columns["colUpdate"].Index == e.ColumnIndex)
                {
                    var row = dtgPatient.Rows[e.RowIndex];
                    if (string.IsNullOrEmpty(row.Cells["colName"].Value as string))
                    {
                        row.Cells["colName"].ErrorText = "Vui lòng nhập tên";
                        return;
                    }
                    else
                    {
                        row.Cells["colName"].ErrorText = "";
                    }

                    var patient = new Patient()
                    {
                        Id = Convert.ToInt32(row.Cells["colId"].Value),
                        Name = row.Cells["colName"].Value.ToString(),
                        Birthday = Convert.ToDateTime(row.Cells["colBirthday"].Value),
                        Address = row.Cells["colAddress"].Value as string,
                        PhoneNumber = row.Cells["colPhone"].Value as string,
                        Sex = Convert.ToBoolean(row.Cells["colSex"].Value)
                    };
                    var result = ServiceManager.Instance.UpdatePatient(patient);
                    if (!result)
                    {
                        MessageBox.Show("Cập nhật thành công");
                    }
                    else
                    {
                        MessageBox.Show("Cập nhật thất bại");
                    }
                }
                else if (dtgPatient.Columns["colDelete"].Index == e.ColumnIndex)
                {
                    var dialog = MessageBox.Show("Bạn có muốn xóa không ?", "Xác nhận", MessageBoxButtons.YesNo);
                    if (dialog == DialogResult.Yes)
                    {
                        var row = dtgPatient.Rows[e.RowIndex];
                        int patientId = Convert.ToInt32(row.Cells["colId"].Value);
                        var result = ServiceManager.Instance.DeletePatient(patientId);
                        if (result)
                        {
                            m_Patients = ServiceManager.Instance.GetAllPatients();
                            dtgPatient.DataSource = m_Patients;
                            lbTotalPatient.Text = m_Patients.Count.ToString();
                        }
                        else
                        {
                            MessageBox.Show("Xóa thất bại");
                        }
                    }
                }
                else if (dtgPatient.Columns["colViewDetail"].Index == e.ColumnIndex)
                {
                    int patientId = Convert.ToInt32(dtgPatient["colId", e.RowIndex].Value);
                    FormPrescriptionManagement form = new FormPrescriptionManagement(patientId);
                    form.ShowDialog();
                }
            }
        }

        private void dtpDateFilter_ValueChanged(object sender, EventArgs e)
        {
            ResetRadios();    
        }

        private void rdDay_CheckedChanged(object sender, EventArgs e)
        {
            string selectedDate = string.Format("{0}{1}{2}", dtpDateFilter.Value.Day, dtpDateFilter.Value.Month, dtpDateFilter.Value.Year);
            FilterPatientByDate(selectedDate);
        }

        private void rdMonth_CheckedChanged(object sender, EventArgs e)
        {
            string selectedMonth = string.Format("{0}{1}", dtpDateFilter.Value.Month, dtpDateFilter.Value.Year);
            FilterPatientByDate(selectedMonth);
        }

        private void rdYear_CheckedChanged(object sender, EventArgs e)
        {
            string selectedYear = string.Format("{0}", dtpDateFilter.Value.Year);
            FilterPatientByDate(selectedYear);
        }

        private void FilterPatientByDate(string date)
        {
            var filteredData = m_Patients.Where(item => item.PatientId != null && item.PatientId.Contains(date)).ToList();
            dtgPatient.DataSource = filteredData;
            lbTotalPatient.Text = filteredData.Count.ToString();
        }

        private void ResetRadios()
        {
            rdDay.Checked = false;
            rdMonth.Checked = false;
            rdYear.Checked = false;    
        }
    }
}
